#import "ALDetailToolbarViewController.h"
#import "NSObject+BlockObservation.h"
#import "NSManagedObjectContext+SMRAdditions.h"
#import "ALCustomEventFilterController.h"
#import "ALVersionsFilterViewController.h"
#import "ALEntryFilter.h"
#import "ALEntry.h"


#pragma mark Constants
static NSString* const kALScopeBarAllGroupIdentifier = @"ALScopeBarAllGroup";
static NSString* const kALScopeBarFilterGroupIdentifier = @"ALScopeBarFilterGroup";


#pragma mark -
@interface ALDetailToolbarViewController ()
@property (nonatomic, retain) NSArrayController *entryFiltersArrayController;
@property (nonatomic, readonly) NSArrayController *intermediateFiltersArrayController;
@property (nonatomic, retain) ALEntryFilter *currentEntryFilter;
-(void)updateEntryFiltersPopoupMenu_;
-(void)updateScopeBarControllerBinding_;
//-(void)loadEntryFilter_:(ALEntryFilter *)entryFilter;
@end


#pragma mark -
@implementation ALDetailToolbarViewController

@synthesize detailScopeBar;
//@synthesize scopeBarArrayController;
@synthesize entriesArrayController;
@synthesize versionsFilterButton;
@synthesize entryFilterPopUpButton;
@synthesize customFilterPopover;
@synthesize customFilterController;
@synthesize versionsFilterPopover;
@synthesize entryFiltersArrayController;
@synthesize currentEntryFilter;
@synthesize intermediateFiltersArrayController;


#pragma mark -
#pragma mark Initialization

-(void)awakeFromNib {
    AMBlockTask entryFiltersMenuTask = ^(id object, NSDictionary *change) {
        [self updateEntryFiltersPopoupMenu_];
    };
    [self addObserverForKeyPath:@"entryFiltersArrayController.arrangedObjects" task:entryFiltersMenuTask];

    NSArrayController *filtersController = [[NSArrayController alloc] init];
    [filtersController setEntityName:[ALEntryFilter entityName]];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"isCustom" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:ALTitleKey ascending:YES], nil];
    [filtersController setSortDescriptors:sortDescriptors];
    [filtersController setAutomaticallyRearrangesObjects:YES];
//    [filtersController setAutomaticallyPreparesContent:YES];
    [filtersController setManagedObjectContext:[self managedObjectContext]];
    [filtersController prepareContent];
    [self setEntryFiltersArrayController:filtersController];
    
    SMRScopeBarGroup *allGroup = [[self detailScopeBar] addGroup];
    [allGroup setShowsSeparator:YES];
    [allGroup setIdentifier:kALScopeBarAllGroupIdentifier];
    
    SMRScopeBarGroup *filterGroup = [[self detailScopeBar] addGroup];
    [filterGroup setShowsSeparator:NO];
    [filterGroup setIdentifier:kALScopeBarFilterGroupIdentifier];
//    [filterGroup bind:kSMRScopeBarContentBinding toObject:[self scopeBarArrayController] withKeyPath:ALArrangedObjectsKey options:nil];
    [[self detailScopeBar] reloadData];

    AMBlockTask selectedEntryFilterTask = ^(id object, NSDictionary *change) {
        [self updateScopeBarControllerBinding_];
    };
    [self addObserverForKeyPath:kALSelectedEntryFilterTitleKey task:selectedEntryFilterTask];
    [self addObserverForKeyPath:@"entriesArrayController" task:selectedEntryFilterTask];

//	AMBlockTask modeTask = ^(id object, NSDictionary *change) {
//	};
//	NSString *modeTaskKeyPath = [NSString stringWithFormat:@"values.%@", ALModeSelection];
//	[[NSUserDefaultsController sharedUserDefaultsController] addObserverForKeyPath:modeTaskKeyPath task:modeTask];
//    [[self detailScopeBar] setIntergroupSpacing:[[self detailScopeBar] intercellSpacing]];
//    NSPopUpButtonCell *scopeBarPopUp = [[self detailScopeBar] popUpButtonCell];
//    [scopeBarPopUp setPullsDown:YES];
//    [self setCurrentEntryFilter:entryFilter];

//    SMRScopeBarGroup *customGroup = [[self detailScopeBar] addGroup];
//    [customGroup setIdentifier:kALDetailToolbarCustomGroupIdentifier];
//    [customGroup setGroupSelectionStyle:SMRScopeBarGroupSelectionStyleRadio];
    
//    [[self tagsArrayController] setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:ALTitleKey ascending:YES]]];
//    SMRScopeBarGroup *tagsGroup = [[self detailScopeBar] addGroup];
//    [tagsGroup setIdentifier:kALDetailToolbarTagGroupIdentifier];
//    [tagsGroup setGroupSelectionStyle:SMRScopeBarGroupSelectionStyleMultipleSelection];
//    [tagsGroup setShowsSeparator:NO];
//    [tagsGroup bind:kSMRScopeBarContentBinding toObject:[self tagsArrayController] withKeyPath:ALArrangedObjectsKey options:nil];
//    NSString *tagsValuesKey = [NSString stringWithFormat:@"%@.%@", ALArrangedObjectsKey, ALTitleKey];
//    [tagsGroup bind:kSMRScopeBarContentValuesBinding toObject:[self tagsArrayController] withKeyPath:tagsValuesKey options:nil];
    
//    [[self detailScopeBar] setSpanSelectionGroups:[NSArray arrayWithObjects:customGroup, tagsGroup, nil]];
//    [[self detailScopeBar] reloadData];
}

-(void)updateScopeBarControllerBinding_ {
    SMRScopeBarGroup *filterGroup = [[self detailScopeBar] groupWithIdentifier:kALScopeBarFilterGroupIdentifier];
    BOOL isBound = [filterGroup infoForBinding:kSMRScopeBarContentBinding] != nil;
    if (isBound)
        [filterGroup unbind:kSMRScopeBarContentBinding];

    NSString *currentFilterTitle = [[NSUserDefaults standardUserDefaults] stringForKey:kALSelectedEntryFilterTitleKey];
    ALEntryFilter *entryFilter = [[self managedObjectContext] smrFetchFirstObjectForEntityName:[ALEntryFilter entityName] withPredicate:@"title LIKE %@", currentFilterTitle];
    NSString *filterKeyPath = [entryFilter intermediateFilterKeyPath];
    NSArrayController *filterController = [self entriesArrayController];
    if (filterKeyPath) {
        filterController = [self intermediateFiltersArrayController];
        [filterController bind:NSContentBinding toObject:[self entriesArrayController] withKeyPath:filterKeyPath options:nil];
    }
    filterKeyPath = [entryFilter primaryFilterKeyPath];    
    [filterGroup bind:kSMRScopeBarContentBinding toObject:filterController withKeyPath:filterKeyPath options:nil];
}


#pragma mark -
#pragma mark Accessors

-(NSPopover *)customFilterPopover {
    if (!customFilterPopover) {
        customFilterPopover = [[NSPopover alloc] init];
        [customFilterPopover setBehavior:NSPopoverBehaviorTransient];
        [customFilterPopover setContentViewController:[self customFilterController]];
    }
    return customFilterPopover;
}

-(NSPopover *)versionsFilterPopover {
    if (!versionsFilterPopover) {
        versionsFilterPopover = [[NSPopover alloc] init];
        [versionsFilterPopover setBehavior:NSPopoverBehaviorTransient];
        ALVersionsFilterViewController *versionsFilterController = [[ALVersionsFilterViewController alloc] initWithNibName:@"VersionsFilterPopover" bundle:[NSBundle mainBundle]];
        [versionsFilterPopover setContentViewController:versionsFilterController];
        [versionsFilterPopover setDelegate:versionsFilterController];
    }
    return versionsFilterPopover;
}

-(ALCustomEventFilterController *)customFilterController {
    if (!customFilterController)
        customFilterController = [[ALCustomEventFilterController alloc] initWithNibName:@"CustomEntryFilter" bundle:[NSBundle mainBundle] windowController:[self windowController] managedObjectContext:[self managedObjectContext]];
    return customFilterController;
}

-(NSArrayController *)intermediateFiltersArrayController {
    if (!intermediateFiltersArrayController) {
        intermediateFiltersArrayController = [[NSArrayController alloc] init];
    }
    return intermediateFiltersArrayController;
}


#pragma mark -
#pragma mark Actions

-(IBAction)filterVersions:(id)sender {
    [[self versionsFilterPopover] showRelativeToRect:NSZeroRect ofView:[self versionsFilterButton] preferredEdge:NSMinYEdge];
}

-(IBAction)changeEntryFilters:(id)sender {
    NSMenuItem *selectedItem = [sender selectedItem];
    [[NSUserDefaults standardUserDefaults] setObject:[selectedItem title] forKey:kALSelectedEntryFilterTitleKey];
//    ALEntryFilter *selectedFilter = [selectedItem representedObject];
//    [self setCurrentEntryFilter:selectedFilter];
}


#pragma mark -
#pragma mark Entry filters

-(void)updateEntryFiltersPopoupMenu_ {
    NSMenu *popupMenu = [[NSMenu alloc] initWithTitle:@"entryFiltersPopUpMenu"];
    NSArray *entryFilters = [[self entryFiltersArrayController] arrangedObjects];
    BOOL switchedToCustomFilters = NO;
    for (ALEntryFilter *entryFilter in entryFilters) {
        if (!switchedToCustomFilters && [entryFilter isCustomValue] == YES) {
            [popupMenu addItem:[NSMenuItem separatorItem]];
            switchedToCustomFilters = YES;
        }
        NSMenuItem *filterMenuItem = [[NSMenuItem alloc] initWithTitle:[entryFilter title] action:NULL keyEquivalent:@""];
        [filterMenuItem setRepresentedObject:entryFilter];
        [popupMenu addItem:filterMenuItem];
    }
    [popupMenu addItem:[NSMenuItem separatorItem]];
    [popupMenu addItemWithTitle:@"Create custom filter…" action:NULL keyEquivalent:@""];
    [[self entryFilterPopUpButton] setMenu:popupMenu];
    
    NSString *defaultSelection = [[NSUserDefaults standardUserDefaults] stringForKey:kALSelectedEntryFilterTitleKey];
    [[self entryFilterPopUpButton] selectItemWithTitle:defaultSelection];
}

//-(void)loadEntryFilter_:(ALEntryFilter *)entryFilter {
//    NSPredicate *filterPredicate = [NSKeyedUnarchiver unarchiveObjectWithData:[entryFilter predicate]];
//    [[self scopeBarArrayController] setFilterPredicate:filterPredicate];
//    [[self scopeBarArrayController] unbind:NSContentBinding];
//    NSString *scopeBarBinding = [NSString stringWithFormat:@"detailViewController.versionsArrayController.arrangedObjects.@distinctUnionOfSets.entries.@distinctUnionOfObjects.%@", [entryFilter entryFilterKeyPath]];
//    [[self scopeBarArrayController] bind:NSContentBinding toObject:[self windowController] withKeyPath:scopeBarBinding options:nil];
//    [self setCurrentEntryFilter:entryFilter];
//    [[self detailScopeBar] reloadData];
//}


#pragma mark -
#pragma mark Scope bar data source

-(NSUInteger)scopeBar:(SMRScopeBar *)scopeBar numberOfObjectsInScopeBarGroup:(NSUInteger)groupIndex {
    SMRScopeBarGroup *group = [scopeBar groupAtIndex:groupIndex];
    if ([[group identifier] isEqualToString:kALScopeBarAllGroupIdentifier])
        return 1;
    return 0;
}

-(id)scopeBar:(SMRScopeBar *)scopeBar valueForObjectInGroup:(NSUInteger)groupIndex atIndex:(NSUInteger)objectIndex {
    SMRScopeBarGroup *group = [scopeBar groupAtIndex:groupIndex];
    if (![[group identifier] isEqualToString:kALScopeBarAllGroupIdentifier])
        return nil;
    return @"All";
}


#pragma mark -
#pragma mark Scope bar delegate

//-(SEL)scopeBar:(SMRScopeBar *)scopeBar actionForObject:(id)object inGroup:(SMRScopeBarGroup *)group {
//    if (![[group identifier] isEqualToString:kALDetailToolbarCustomGroupIdentifier])
//        return NULL;
//    if (![object isEqual:@"Custom"])
//        return NULL;
//    return @selector(customGroupWasClicked:);
//}

//-(void)customGroupWasClicked:(id)sender {
//    NSUInteger groupIndex = [[self detailScopeBar] indexOfGroup:sender];
//    NSRect buttonRect = [[self detailScopeBar] rectForObjectIndex:1 groupIndex:groupIndex];
//    [[self customFilterPopover] showRelativeToRect:buttonRect ofView:[self detailScopeBar] preferredEdge:NSMinYEdge];
//    NSArray *selectedEntries = [[[self customFilterController] entriesArrayController] selectedObjects];
//    [[NSNotificationCenter defaultCenter] postNotificationName:ALCustomEntryFilterDidChangeNotification object:selectedEntries];
//}

@end
